package com.tiancheng.trade.settlement.service.settlement.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tiancheng.trade.commom.core.data.PageInfo;
import com.tiancheng.trade.settlement.mapper.settlement.SettleDetailMapper;
import com.tiancheng.trade.settlement.model.order.SubOrder;
import com.tiancheng.trade.settlement.model.settlement.SettleDetail;
import com.tiancheng.trade.settlement.service.order.ISubOrderService;
import com.tiancheng.trade.settlement.service.settlement.ISettleDetailService;
import com.tiancheng.trade.settlement.util.JsonUtil;
import com.tiancheng.trade.settlement.util.ObjectConvertUtil;
import com.tiancheng.trade.settlement.vo.settlement.admin.SettleDetailQueryVo;
import com.tiancheng.trade.settlement.vo.settlement.admin.res.SettleDetailResVo;
import com.tiancheng.trade.settlement.vo.settlement.admin.res.SettleExceptionDataResVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * * 交易资金对账明细表service 实现
 *
 * @author likailun
 * @date 2021/3/30
 */
@Service
@Slf4j
public class SettleDetailServiceImpl extends ServiceImpl<SettleDetailMapper, SettleDetail> implements ISettleDetailService {

    @Resource
    private SettleDetailMapper settleDetailMapper;
    @Resource
    private ISubOrderService subOrderService;

    @Override
    public PageInfo<SettleDetailResVo> findList(SettleDetailQueryVo detailQueryVo) {
        QueryWrapper<SettleDetail> conditions = new QueryWrapper<SettleDetail>();
        conditions.eq("check_code", detailQueryVo.getCheckCode());
        if(!CollectionUtils.isEmpty(detailQueryVo.getDifferentTypes())){
            conditions.in("different_type", detailQueryVo.getDifferentTypes());
        }
        PageInfo<SettleDetail> page = settleDetailMapper.find(conditions, detailQueryVo.getCurrentPage(), detailQueryVo.getPageSize());
        List<SettleDetail> list = page.getList();
        return new PageInfo<SettleDetailResVo>(this.getSettleDetailResVos(list), page.getPagination());
    }

    @Override
    public SettleExceptionDataResVo findExceptionData(String checkCode) {
        Map<String, Object> sb = settleDetailMapper.getSumAmountByGroupCode(checkCode);

        SettleExceptionDataResVo resVo = new SettleExceptionDataResVo();
        if(null!=sb){
            log.info("查询对账异常信息，，对账编号：{}，结果：{}",checkCode, JsonUtil.toJson(sb));
            resVo.setPlatformHasAmount(MapUtils.getInteger(sb,"platformHasAmount",0));
            resVo.setPlatformNoneAmount(MapUtils.getInteger(sb,"platformNoneAmount",0));
            resVo.setBilateralAmount(MapUtils.getInteger(sb,"bilateralAmount",0));
        }
        return resVo;
    }

    @Override
    public List<SettleDetailResVo> pageByCheckCodes(Set<String> checkCodes,int startId,int start,int size) {
        List<SettleDetail> list = settleDetailMapper.pageByCheckCodes(checkCodes, startId, start, size);
        return this.getSettleDetailResVos(list);
    }

    @Override
    public Long countByCheckCodes(Set<String> checkCodes) {
        QueryWrapper<SettleDetail> conditions = new QueryWrapper<SettleDetail>();
        conditions.in("check_code", checkCodes);
        return settleDetailMapper.selectCount(conditions);
    }

    /**
     * 对账明细转换，补全子订单信息
     * @param list 对账明细记录
     * @return
     */
    private List<SettleDetailResVo> getSettleDetailResVos(List<SettleDetail> list) {
        List<SettleDetailResVo> settleDetailResVos = null;
        if (list.size() > 0) {
            settleDetailResVos=new ArrayList<>(list.size());
            List<String> subOrderIds = list.stream().map(SettleDetail::getSubOrderId).collect(Collectors.toList());
            List<SubOrder> subOrders = subOrderService.findBySubOrderIds(subOrderIds);
            for (SettleDetail settleDetail : list) {
                SettleDetailResVo detailResVo = ObjectConvertUtil.convert(settleDetail, SettleDetailResVo.class).get();
                List<SubOrder> collect = subOrders.stream().filter(subOrder -> subOrder.getSubOrderId().equals(settleDetail.getSubOrderId())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(collect)) {
                    detailResVo.setSubOrderAmount(collect.get(0).getSubOrderAmount());
                    detailResVo.setPayAmount(collect.get(0).getPayAmount());
                    detailResVo.setRefundAmount(collect.get(0).getRefundAmount());
                    detailResVo.setIsCoupon(collect.get(0).getIsCoupon());
                    detailResVo.setDiscount(collect.get(0).getDiscount());
                    detailResVo.setSubOrderStatus(collect.get(0).getSubOrderStatus());
                    detailResVo.setBizStatus(collect.get(0).getBizStatus());
                    detailResVo.setRefundStatus(collect.get(0).getRefundStatus());
                    detailResVo.setVerificationTime(collect.get(0).getVerificationTime());
                    detailResVo.setVerificationStatus(collect.get(0).getVerificationStatus());
                    detailResVo.setOrderCreateDt(collect.get(0).getCreatedDt());
                    detailResVo.setMerchantCode(collect.get(0).getMerchantCode());
                    detailResVo.setMerchantName(collect.get(0).getMerchantName());
                }
                settleDetailResVos.add(detailResVo);
            }

        }
        return settleDetailResVos;
    }

}
